{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Example: Alternative initial plasma flux guesses\n", "\n", "---\n", "\n", "In both **static forward** and **static inverse** Grad-Shafranov (GS) solves, FreeGSNKE's Newton-Krylov solver starts from an initial guess for the plasma poloidal flux $\\psi_{p}$. Recall tht total poloidal flux is $\\psi = \\psi_p + \\psi_c$ where $\\psi_c$ is the flux from the conducting structures. \n", "\n", "While the default Gaussian guess is sufficient for many equilibria, a physically motivated initial guess that better approximates the expected plasma location, elongation, and plasma current can reduce the number of Newton-Krylov iterations and improve convergence for some configurations.\n", "\n", "This notebook demonstrates how to configure and compare FreeGSNKE's different initial flux guess constructors on a **MAST-U-like tokamak**.\n", "\n", "**Note:** It is recommended to review `example01a` (static inverse) and `example02a` (static forward) before running this notebook, as shared setup details are kept brief here." ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "### Import packages" ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import pickle\n", "import time\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "from freegsnke import GSstaticsolver, build_machine, equilibrium_update\n", "from freegsnke.equilibrium import PsiGuessGaussian, PsiGuessParabolicJtor\n", "from freegsnke.jtor_update import ConstrainPaxisIp" ] }, { "cell_type": "markdown", "id": "3", "metadata": {}, "source": [ "### Create the machine object\n", "\n", "Build the MAST-U-like tokamak from the packaged machine configuration pickle files. " ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "tokamak = build_machine.tokamak(\n", " active_coils_path=\"../machine_configs/MAST-U/MAST-U_like_active_coils.pickle\",\n", " passive_coils_path=\"../machine_configs/MAST-U/MAST-U_like_passive_coils.pickle\",\n", " limiter_path=\"../machine_configs/MAST-U/MAST-U_like_limiter.pickle\",\n", " wall_path=\"../machine_configs/MAST-U/MAST-U_like_wall.pickle\",\n", ")" ] }, { "cell_type": "markdown", "id": "5", "metadata": {}, "source": [ "### Instantiate an equilibrium and profile object" ] }, { "cell_type": "code", "execution_count": null, "id": "6", "metadata": {}, "outputs": [], "source": [ "# initialise equilibrium and profiles\n", "eq = equilibrium_update.Equilibrium(\n", " tokamak=tokamak,\n", " Rmin=0.1,\n", " Rmax=2.0,\n", " Zmin=-2.2,\n", " Zmax=2.2,\n", " nx=65, # must be of the form (2**n + 1)\n", " ny=129, # must be of the form (2**n + 1)\n", ")\n", "\n", "profiles = ConstrainPaxisIp(\n", " eq=eq, # equilibrium object\n", " paxis=8e3, # profile object\n", " Ip=6e5, # plasma current\n", " fvac=0.5, # fvac = rB_{tor}\n", " alpha_m=1.8, # profile function parameter\n", " alpha_n=1.2 # profile function parameter\n", ")" ] }, { "cell_type": "markdown", "id": "7", "metadata": {}, "source": [ "### 1. Gaussian-shape plasma flux (`PsiGuessGaussian`)\n", "\n", "The default initial guess in the `eq` object uses a Gaussian-shaped plasma flux distribution defined in **normalised grid coordinates** $(x, y) \\in [0, 1]^2$:\n", "\n", "$$\n", "\\psi_p(x, y) = \\exp\\!\\left(C - \\left(|x - x_c|^p + |y - y_c|^p\\right)\\right),\n", "$$\n", "\n", "with $\\psi_p = 0$ enforced on the computational domain boundary. \n", "\n", "The parameters for this guess are supplied via `gpars=(xc, yc, C, p)` (defaulting to `(0.5, 0.5, 0, 2)`)." ] }, { "cell_type": "code", "execution_count": null, "id": "8", "metadata": {}, "outputs": [], "source": [ "# initialise the class \n", "plasma_psi_gaussian = PsiGuessGaussian(gpars=(0.5, 0.5, 0.0, 2.0))" ] }, { "cell_type": "markdown", "id": "9", "metadata": {}, "source": [ "### 2. Parabolic-shaped current density guess (`PsiGuessParabolicJtor`)\n", "\n", "This alternative guess assumes the core plasma boundary can be approximated by an ellipse with centre $(h, k)$ and semi-axes $(a, b)$, where the elliptic coordinate $E(R, Z)$ satisfies $E(h, k) = 0$ and $E(R, Z) = 1$ on the boundary. \n", "\n", "An approxaimte parabolic toroidal current density profile\n", "\n", "$$\n", "J_{\\text{tor}}(R, Z) = \\hat{J}\\left(1 - E(R, Z)^i\\right)^j\n", "$$\n", "\n", "is scaled via $\\hat{J}$ to match the prescribed plasma current $I_p$, and a single linear Grad-Shafranov solve yields the initial $\\psi_p$ guess (see [Wai et al., (2026)](https://iopscience.iop.org/article/10.1088/1741-4326/ae203c/meta)).\n", "\n", "The parameters for this type of gues can be constructed in three ways:\n", "1. **Direct ellipse parameters**: `PsiGuessParabolicJtor(h, k, a, b, Ip, psi_scale=1.0)`.\n", "2. **X-point and midplane coordinates**: `PsiGuessParabolicJtor.from_xpoint_and_midplane(Rx, Zx, Ri, Ro, Zm, Ip)`, which sets $h = (R_x + R_i + R_o)/3$.\n", "3. **LCFS points**: `PsiGuessParabolicJtor.from_separatrix_points(Ip, *points)`, which fits $(h, k, a, b)$ to four or more points on a user-provided plasma boundary using ordinary least squares (OLS).\n", "\n", "Depending on which information you have available prior to a solve, you can choose either of the three above. " ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "# let's construct all three types below\n", "\n", "# type 1 (direct ellipse parameterisation)\n", "plasma_psi_parabolic_standard = PsiGuessParabolicJtor(\n", " h = (min(tokamak.limiter.R)+max(tokamak.limiter.R))/2, # centre of ellipse (R)\n", " k = 0.0, # centre of ellipse (Z)\n", " a = 0.5, # roughly the minor radius of the plasma\n", " b = 0.5 * 2, # roughly the minor radius times the elongation of expected plasma\n", " Ip = profiles.Ip, # plasma current (to scale the guess)\n", " psi_scale = 1.0 # might need to vary this default\n", " )\n", "\n", "# type 2 (use approximate up/down symmetric X-point locations and midplane)\n", "Rx, Zx = 0.6, 1.1\n", "Ri, Ro, Zm = 0.34, 1.4, 0.0\n", "\n", "plasma_psi_parabolic_xpoints = PsiGuessParabolicJtor.from_xpoint_and_midplane(\n", " Rx=Rx, Zx=Zx, Ri=Ri, Ro=Ro, Zm=Zm, Ip=profiles.Ip,\n", ")\n", "\n", "# type 3 (use approximate LCFS points)\n", "plasma_psi_parabolic_lcfs = PsiGuessParabolicJtor.from_separatrix_points(\n", " profiles.Ip,\n", " (Rx, Zx), (Rx, -Zx), (Ri, Zm), (Ro, Zm),\n", ")" ] }, { "cell_type": "markdown", "id": "11", "metadata": {}, "source": [ "Let us visualise four of these initial $\\psi_p$ guesses side by side inside the MAST-U machine." ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "initial_cases = [\n", " (\"Default Gaussian\", plasma_psi_gaussian),\n", " (\"Parabolic (direct ellipse)\", plasma_psi_parabolic_standard),\n", " (\"Parabolic (X-pt & midplane)\", plasma_psi_parabolic_xpoints),\n", " (\"Parabolic (LCFS)\", plasma_psi_parabolic_lcfs),\n", "]\n", "\n", "# plot\n", "fig, axes = plt.subplots(1, 4, figsize=(14, 6), dpi=80, sharex=True, sharey=True)\n", "for ax, (title, case) in zip(axes, initial_cases):\n", " ax.grid(True, alpha=0.5)\n", " ax.set_aspect(\"equal\")\n", " tokamak.plot(axis=ax, show=False)\n", " ax.plot(tokamak.wall.R, tokamak.wall.Z, \"k\", linewidth=1.2)\n", " case.plasma_psi = case(eq=eq)\n", " levels = np.linspace(np.min(case.plasma_psi), np.max(case.plasma_psi), 25)\n", " ax.contour(eq.R, eq.Z, case.plasma_psi, levels=levels)\n", " ax.set_title(title, fontsize=10)\n", " ax.set_xlim(0.1, 2.15)\n", " ax.set_ylim(-2.25, 2.25)\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "If we now initialise the coil currents inside the `eq` object, we can construct the coil flux and add it to the plasma flux guesses above. This will show us what the total flux passes to the static solver looks like during the first Newton-Krylov iteration. " ] }, { "cell_type": "code", "execution_count": null, "id": "14", "metadata": {}, "outputs": [], "source": [ "# set coil currents\n", "with open(\"data/simple_diverted_currents_PaxisIp.pk\", \"rb\") as f:\n", " diverted_currents = pickle.load(f)\n", "\n", "for key, val in diverted_currents.items():\n", " eq.tokamak.set_coil_current(coil_label=key, current_value=val)\n", " \n", "# flux from the coils\n", "psi_coils = eq.tokamak.calcPsiFromGreens(pgreen=eq._pgreen)" ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "# plot just flux from coils\n", "fig1, ax1 = plt.subplots(1, 1, figsize=(3, 6), dpi=80)\n", "ax1.grid(True, which='both')\n", "ax1.plot(tokamak.wall.R, tokamak.wall.Z, 'k')\n", "eq.tokamak.plot(axis=ax1, show=False)\n", "ax1.contour(eq.R, eq.Z, psi_coils, levels=25)\n", "ax1.set_xlim(0.1, 2.15)\n", "ax1.set_ylim(-2.25, 2.25)\n", "plt.tight_layout()" ] }, { "cell_type": "markdown", "id": "16", "metadata": {}, "source": [ "Notice how the total flux maps shown below are starting to look like Grad-Shafranov equilibria! The solver can then work with these guesses to converge to tolerance (as we'll see next)." ] }, { "cell_type": "code", "execution_count": null, "id": "17", "metadata": {}, "outputs": [], "source": [ "# now plot flux from coils with the different plasma flux guesses\n", "fig, axes = plt.subplots(1, 4, figsize=(14, 6), dpi=80, sharex=True, sharey=True)\n", "for ax, (title, case) in zip(axes, initial_cases):\n", " ax.grid(True, alpha=0.5)\n", " ax.set_aspect(\"equal\")\n", " tokamak.plot(axis=ax, show=False)\n", " ax.plot(tokamak.wall.R, tokamak.wall.Z, \"k\", linewidth=1.2)\n", " total_flux = case.plasma_psi + psi_coils\n", " levels = np.linspace(np.min(total_flux), np.max(total_flux), 25)\n", " ax.contour(eq.R, eq.Z, total_flux, levels=levels)\n", " ax.set_title(title, fontsize=10)\n", " ax.set_xlim(0.1, 2.15)\n", " ax.set_ylim(-2.25, 2.25)\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "18", "metadata": {}, "source": [ "---\n", "### Static forward solve comparison\n", "\n", "To quantify the effect of the initial plasma flux guess on solver convergence, we solve the same diverted forward equilibrium from each initial guess. \n", "\n", "We can store the GS residual at each iteration for comparison." ] }, { "cell_type": "code", "execution_count": null, "id": "19", "metadata": {}, "outputs": [], "source": [ "# initialise solver object\n", "solver = GSstaticsolver.NKGSsolver(eq, gs_operator_order=4)" ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "# run each of the solves\n", "results = {}\n", "for label, case in initial_cases:\n", "\n", " # initial guess\n", " eq.plasma_psi = case.plasma_psi\n", " \n", " # timer\n", " t0 = time.perf_counter()\n", " \n", " # solve\n", " solver.solve(\n", " eq=eq,\n", " profiles=profiles,\n", " target_relative_tolerance=1e-9,\n", " verbose=False,\n", " )\n", " elapsed = time.perf_counter() - t0\n", "\n", " # store results\n", " results[label] = {\n", " \"psi_final\": eq.plasma_psi.copy(),\n", " \"residual\": np.asarray(solver.norm_rel_change),\n", " \"initial_res\": solver.initial_rel_residual,\n", " \"iters\": len(solver.norm_rel_change) - 1,\n", " \"time_taken\": elapsed,\n", " }\n", " print(\n", " f\"{label:28s} | iters: {results[label]['iters']:2d} \"\n", " f\"| init residual: {results[label]['initial_res']:.3e} \"\n", " f\"| final residual: {results[label]['residual'][-1]:.3e} \"\n", " f\"| time: {elapsed:.3f} s\"\n", " )" ] }, { "cell_type": "markdown", "id": "21", "metadata": {}, "source": [ "Now let's plot the history of the residual from each solve to see the iterations taken. " ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "fig, ax1 = plt.subplots(1, 1, figsize=(4.5, 4), dpi=90)\n", "\n", "for label, res in results.items():\n", " ax1.semilogy(\n", " np.arange(len(res[\"residual\"])),\n", " res[\"residual\"],\n", " marker=\"o\",\n", " markersize=4,\n", " label=label,\n", " )\n", "ax1.axhline(1e-9, color=\"k\", linestyle=\"--\", linewidth=1.0, label=\"Convergence tolerance\")\n", "ax1.set_xlabel(\"Iteration\")\n", "ax1.set_ylabel(\"Relative GS residual\")\n", "ax1.grid(True, which=\"both\", alpha=0.4)\n", "ax1.legend(fontsize=8)\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "23", "metadata": {}, "source": [ "While the default Gaussian guess is acceptable for most use cases, convergence can be **accelerated** using the parabolic Jtor guess if certain features of the plasma core shape are known before simulation!" ] } ], "metadata": { "kernelspec": { "display_name": "freegsnke", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }